package com.edianping.main;


import com.daguu.lib.httpsqs4j.HttpsqsClient;
import com.edianping.config.AppConfigBean;
import com.edianping.thread.ProductScoreProcessThread;
import com.edianping.thread.ShopInfoProcessThread;
import com.edianping.thread.ShopScoreProcessThread;
import com.edianping.thread.ThreadPoolHandle;
import com.edianping.timer.MyTimerTask;

/**
 * 程序的主要流程
 * 一个MainTask对应于websites.xml中的一个<website>
 * 包含多个Url，以及其所对应的配置文件
 * 
 * @author jszhang
 * 
 */
public class MainTask extends MyTimerTask {
	int interval = 100000;
	
	public ThreadPoolHandle tp_handle = null;
	public double MaxIterNum = 0.001; //所有Task中运行的最大次数（加权后的）

	private HttpsqsClient client = null;
	private AppConfigBean acb = null;

	/**
	 * Maintask类的初始化
	 * 
	 * @param wsb
	 * @param sb
	 * @param isTest :
	 *            if true . only open one thread in the threadpool
	 */
	public MainTask( AppConfigBean acb, HttpsqsClient client ) {
		this.acb = acb;
		this.client = client;
		
		initThreadPoolHandle();
	}

	/**
	 * 初始化线程池 
	 * Hardcode 了线程池的线程数目
	 */
	void initThreadPoolHandle() {
		
		//全部Task使用一个线程池
		if(tp_handle==null){
			tp_handle = new ThreadPoolHandle( acb.getThreadpoosize() );
		}
	}

	/**
	 * 覆写run()方法,这里将任务加入线程池队列。 当然要等Timer调度到这个Task，它才会开始运行
	 */
	public void run() {
		if (!tp_handle.isAlive()) {
			tp_handle.shutdown();
			tp_handle = null; // wait gc
			initThreadPoolHandle();// create a new TheadPool
		}

		//according to the configuration file init thread pool
//		for ( int i=0; i<acb.getProcessTaskCount(); i++ ) {
			ShopScoreProcessThread tx = new ShopScoreProcessThread( client, acb.getProcessConfigBean(), acb.getMinShopProcessReviewCount() );
			tp_handle.enqueue(tx);
//		}
			
			ShopInfoProcessThread tx2 = new ShopInfoProcessThread( client, acb.getProcessConfigBean() );
			tp_handle.enqueue(tx2);
			
			ProductScoreProcessThread tx3 = new ProductScoreProcessThread( client, acb.getProcessConfigBean(), acb.getMinProductProcessReviewCount() );
			tp_handle.enqueue(tx3);
	}

}
